#include "timeout_manager.hpp"
#include <iostream>

namespace timeout_manager {

// TimeoutManager的构造和析构函数
TimeoutManager::TimeoutManager(size_t threadPoolSize, size_t timerWheelSize, Duration timerTick)
    : threadPool_(std::make_unique<ThreadPool>(threadPoolSize)),
      timerWheel_(std::make_unique<TimerWheel>(timerWheelSize, timerTick)),
      nextTaskId_(1) {
    
    std::cout << "创建超时管理器" << std::endl;
    std::cout << "启动超时管理器组件..." << std::endl;
    
    // 启动时间轮
    timerWheel_->start();
    
    std::cout << "超时管理器初始化完成" << std::endl;
}

TimeoutManager::~TimeoutManager() {
    std::cout << "正在关闭超时管理器..." << std::endl;
    
    // 停止时间轮
    if (timerWheel_) {
        timerWheel_->stop();
    }
    
    // 取消所有活跃任务
    {
        std::lock_guard<std::mutex> lock(tasksMutex_);
        for (const auto& pair : activeTasks_) {
            std::cout << "取消活跃任务: ID=" << pair.first << std::endl;
            pair.second->cancel();
        }
        activeTasks_.clear();
    }
    
    std::cout << "超时管理器已关闭" << std::endl;
    std::cout << "销毁超时管理器" << std::endl;
}

bool TimeoutManager::cancelTask(const TaskHandle& handle) {
    auto taskId = handle.getId();
    
    std::cout << "尝试取消任务: ID=" << taskId << std::endl;
    
    std::shared_ptr<TaskCanceller> canceller;
    
    // 从活跃任务中查找并移除
    {
        std::lock_guard<std::mutex> lock(tasksMutex_);
        auto it = activeTasks_.find(taskId);
        if (it == activeTasks_.end()) {
            std::cout << "任务不存在或已完成: ID=" << taskId << std::endl;
            return false;
        }
        
        canceller = it->second;
        activeTasks_.erase(it);
    }
    
    // 取消任务
    if (canceller) {
        canceller->cancel();
    }
    
    // 移除定时器
    timerWheel_->removeTimer(taskId);
    
    cancelledTasks_.fetch_add(1);
    std::cout << "任务取消成功: ID=" << taskId << std::endl;
    return true;
}

TimeoutManager::Statistics TimeoutManager::getStatistics() const {
    std::lock_guard<std::mutex> lock(tasksMutex_);
    
    return {
        totalTasks_.load(),
        completedTasks_.load(),
        timeoutTasks_.load(),
        cancelledTasks_.load(),
        activeTasks_.size(),
        threadPool_->getQueueSize()
    };
}

TimeoutManager& TimeoutManager::getInstance() {
    static TimeoutManager instance;
    return instance;
}

uint64_t TimeoutManager::generateTaskId() {
    return nextTaskId_.fetch_add(1);
}

void TimeoutManager::cleanupTask(uint64_t taskId) {
    std::lock_guard<std::mutex> lock(tasksMutex_);
    activeTasks_.erase(taskId);
    
    // 移除对应的定时器
    timerWheel_->removeTimer(taskId);
}

} // namespace timeout_manager